package com.qianxing.utils;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.KeyPairGenerator;

/**
 * 密钥生成工具类
 *
 * @Author:LongShengjie
 * @Since:2024/2/19 11:31
 */
public class KeyGeneratorUtils {

    private static final String ALGORITHM_ONE = "AES";
    private static final String ALGORITHM_TWO = "DES";
    private static final String ALGORITHM_THREE = "RSA";

    //生成AES密钥
    public static String generatorAESKey() throws NoSuchAlgorithmException {
        // 创建一个KeyGenerator实例，并指定使用AES算法
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_ONE);//采用AES加密算法

        // 设置SecureRandom用于生成随机数
        SecureRandom secureRandom = new SecureRandom();
        keyGenerator.init(256, secureRandom); // 指定密钥长度为256位，即32字节

        // 生成AES密钥
        SecretKey secretKey = keyGenerator.generateKey();

        // 输出生成的密钥
        byte[] encodedKey = secretKey.getEncoded();
        System.err.println("生成的密钥:" + encodedKey);
        System.out.println("AES密钥的十六进制字符串表示：" + bytesToHex(encodedKey));
        return bytesToHex(encodedKey);
    }

    // 生成DES密钥
    public static String generateDESKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        SecureRandom secureRandom = new SecureRandom();
        keyGenerator.init(56, secureRandom); // 指定DES密钥长度为56位，即7字节
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] encodedKey = secretKey.getEncoded();
        System.out.println("DES密钥的十六进制字符串表示：" + bytesToHex(encodedKey));
        return bytesToHex(encodedKey);
    }

    // 生成RSA密钥对
    public static String[] generateRSAKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom();
        keyPairGenerator.initialize(2048, secureRandom); // 指定RSA密钥长度为2048位
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        System.out.println("RSA公钥：" + bytesToHex(keyPair.getPublic().getEncoded()));
        System.out.println("RSA私钥：" + bytesToHex(keyPair.getPrivate().getEncoded()));
        String[] strArr = new String[2];
        //RSA公钥
        strArr[0] = "RSA公钥:" + bytesToHex(keyPair.getPublic().getEncoded());
        //RSA私钥
        strArr[1] = "RSA私钥:" + bytesToHex(keyPair.getPrivate().getEncoded());
        return strArr;
    }

    // 将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexStringBuilder = new StringBuilder();
        for (byte b : bytes) {
            hexStringBuilder.append(String.format("%02X", b));
        }
        return hexStringBuilder.toString();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String AesKey = generatorAESKey();
        System.err.println(AesKey);
    }
}
